package generic.hornetq;

import java.util.HashMap;
import java.util.Map;

import generic.Publisher;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;

import org.hornetq.api.core.DiscoveryGroupConfiguration;
import org.hornetq.api.core.TransportConfiguration;
import org.hornetq.api.jms.HornetQJMSClient;
import org.hornetq.api.jms.JMSFactoryType;
import org.hornetq.core.remoting.impl.netty.NettyConnectorFactory;
import org.hornetq.jms.client.HornetQConnectionFactory;

public class HornetQPublisher implements Publisher {

	Session session;
	MessageProducer messageProducer;

	private String url = "localhost";
	private int port = 5445;

	private StringBuilder builder;

	public HornetQPublisher(String url, int port) {
		super();
		this.url = url;
		this.port = port;

		builder = new StringBuilder();

		initialize(url);

		System.out.println("HornetQPublisher ready to publish messages...");
	}

	private void initialize(String brokerUrl) {
		try {
			Map<String, Object> connectionParams = new HashMap<String, Object>();

			connectionParams.put(org.hornetq.core.remoting.impl.netty.TransportConstants.HOST_PROP_NAME, url);
			connectionParams.put(org.hornetq.core.remoting.impl.netty.TransportConstants.PORT_PROP_NAME, port);

			TransportConfiguration transportConfiguration = 
			    new TransportConfiguration(
			    "org.hornetq.core.remoting.impl.netty.NettyConnectorFactory", 
			    connectionParams);
			
			//HornetQConnectionFactory connectionFactory = HornetQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, transportConfiguration);
			
			DiscoveryGroupConfiguration dgc = new DiscoveryGroupConfiguration("231.7.7.7", 9876);
			HornetQConnectionFactory connectionFactory = HornetQJMSClient.createConnectionFactoryWithHA(dgc, JMSFactoryType.CF);
			
			connectionFactory.setFailoverOnInitialConnection(true);
			
			Connection connection = connectionFactory.createConnection();

			session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
			//session.createTopic("OrderQueue2");

			Topic topic = HornetQJMSClient.createTopic("OrderQueue2");
			
			messageProducer = session.createProducer(topic);

			connection.start();
		} catch (JMSException e) {
			e.printStackTrace();
		}
	}

	@Override
	public boolean send(String message) {
		boolean result = false;
		try {
			TextMessage textMessage = session.createTextMessage(message);
			messageProducer.send(textMessage);
			result = true;
		} catch (JMSException e) {
			e.printStackTrace();
		}
		return result;
	}

}
